#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <stdlib.h>

#include <map>

#define REF 956703932

typedef unsigned int uint;
typedef unsigned long ulong;

uint get_time_slice(ulong ts) {
	return 1 + (ts-956703932)/(24*3600*30);
}

int main(int ac, char** av) {
	srand(time(NULL));

	std::ifstream inp;
	std::ofstream train, test;
	
	inp.open("ratings.dat");	
	train.open("train_data.txt", std::ios::out);
	test.open("test_data.txt", std::ios::out);
	
	uint movie_id, user_id, vote; 
	ulong ts;
	ulong total_votes = 0;
	std::string line;
	
	uint prev_user_id = 0;
	uint count = 0;
	while (inp.good()) {
		std::getline(inp,line);
		if (line.empty()) break;
		sscanf(line.c_str(),"%u::%u::%u::%lu",&user_id,&movie_id,&vote,&ts);
		
		if (prev_user_id != user_id) {
			prev_user_id = user_id;	
			count = 0;
			train << get_time_slice(ts) << ' ' << user_id << ' ' << movie_id << ' ' << vote << std::endl;	
		}
		else {
			double rr = (double)rand()/(double)(RAND_MAX+1.0);
			if (rr < 0.5 && count <= 10) {
				test << get_time_slice(ts) << ' ' << user_id << ' ' << movie_id << ' ' << vote << std::endl;	
				++count;
			}
			else {
				train << get_time_slice(ts) << ' ' << user_id << ' ' << movie_id << ' ' << vote << std::endl;	
			}	
		}
		++total_votes;
	}
	
	inp.close();
	train.close();
	test.close();
	printf("Finished .. # Ratings = %lu\n", total_votes);
}
